package stack;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Stack;

public class nextGreaterElement {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] result = new int[nums1.length];
        Arrays.fill(result, -1);
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], i);
        }
        Stack<Integer> integers = new Stack<>();
        for (int i = 0; i < nums2.length; i++) {
            while (!integers.isEmpty() && nums2[i] > nums2[integers.peek()]){
                int pre = nums2[integers.pop()];
                if (map.containsKey(pre)){
                    result[map.get(pre)] = nums2[i];
                }
            }
            integers.push(i);
        }
        return result;
    }
}
